package com.mp.approvalreq.servlet.component;

import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.ContentType;
import com.mp.approvalreq.entity.dto.ComponentGroupDTO;
import com.mp.approvalreq.entity.vo.Component;
import com.mp.approvalreq.entity.vo.ComponentGroupVO;
import com.mp.approvalreq.service.ApprovalOperateServicePrx;
import com.mp.approvalreq.servlet.AbstractServlet;
import com.mp.approvalreq.util.ApprovalUtils;
import com.mp.approvalreq.util.ListHelper;
import com.mp.approvalreq.util.ServiceUtils;
import com.mp.user.entity.User;
import com.plusmoney.exception.RpcServerLogicalException;
import com.plusmoney.message.SuccessMsg;
import com.plusmoney.util.Utils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author liuqi
 * @date 2018/9/18
 */
@WebServlet("/saveComponentGroup")
public class SaveComponentGroup extends AbstractServlet {
    private static final Logger logger = LoggerFactory.getLogger(SaveComponentGroup.class);

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            User user = getReqUser(req);
            if (!ApprovalUtils.isApprovalAdmin(user)) {
                throw new RpcServerLogicalException(1, "无权操作");
            }

            String content = getContent(req);
            logger.info("json:{}", content);

            ComponentGroupVO componentGroupVO = JSONObject.parseObject(content, ComponentGroupVO.class);
            check(componentGroupVO);

            ComponentGroupDTO componentGroupDTO = initComponentGroupDTO(componentGroupVO, user.getCompanyId());

            ApprovalOperateServicePrx approvalOperateService = ServiceUtils.getApprovalOperateServicePrx();
            Integer groupId = approvalOperateService.addComponentGroup(componentGroupDTO, user.getCompanyId());

            if (Utils.isNull(groupId)) {
                throw new RpcServerLogicalException(1, "网络繁忙,请稍后再试");
            }

            if (Utils.isNotNull(componentGroupVO.getId())) {
                approvalOperateService.delComponentGroup(user.getCompanyId(), componentGroupVO.getId());
            }

            printJson(resp, SuccessMsg.getDefaultMsg(groupId));
        } catch (Throwable e) {
            onThrowable(req, resp, e);
        }
    }

    private ComponentGroupDTO initComponentGroupDTO(ComponentGroupVO componentGroupVO, Integer companyId) {
        ComponentGroupDTO componentGroupDTO = new ComponentGroupDTO();

        componentGroupDTO.setCompanyId(companyId);
        componentGroupDTO.setName(componentGroupVO.getName());
        componentGroupDTO.setComponents(componentGroupVO.getComponents());

        int size = getComponentSize(componentGroupVO.getComponents());
        componentGroupDTO.setSize(size);

        componentGroupDTO.setIsCommonGroup(componentGroupVO.getIsCommonGroup());
        componentGroupDTO.setIsAddComponentGroup(componentGroupVO.getIsAddComponentGroup());

        return componentGroupDTO;
    }

    private int getComponentSize(List<Component> components) {
        int size = 0;
        for (Component component : components) {
            if (component.getType() == ContentType.TIME_RANGE) {
                size++;
            }
        }
        return (size == 0 ? components.size() : components.size() + 1 - size);
    }

    private void check(ComponentGroupVO componentGroupVO) {
        if (Utils.isNull(componentGroupVO)) {
            throw new RpcServerLogicalException(1, "参数错误");
        }

        if (StringUtils.isEmpty(componentGroupVO.getName()) || StringUtils.isEmpty(componentGroupVO.getName().trim())) {
            throw new RpcServerLogicalException(1, "参数错误");
        }

        if (Utils.isNull(componentGroupVO.getIsAddComponentGroup())) {
            throw new RpcServerLogicalException(1, "是否添加多个组件集不能为空");
        }

        if (Utils.isNull(componentGroupVO.getIsCommonGroup())) {
            throw new RpcServerLogicalException(1, "是否为通用组件集不能为空");
        }

        if (ListHelper.isNullEmpty(componentGroupVO.getComponents())) {
            throw new RpcServerLogicalException(1, "参数错误");
        } else {
            for (Component component : componentGroupVO.getComponents()) {
                if (Utils.isNull(component.getType())) {
                    throw new RpcServerLogicalException(1, "类型不能为空");
                }

                if (Utils.isNull(component.getNeed())) {
                    throw new RpcServerLogicalException(1, "必填选项不能为空");
                }

                if (Utils.isNull(component.getNum())) {
                    throw new RpcServerLogicalException(1, "组件编号不能为空");
                }

                if (StringUtils.isEmpty(component.getName()) || StringUtils.isEmpty(component.getName().trim())) {
                    throw new RpcServerLogicalException(1, "组件名不能为空");
                }

                if (component.getType() == ContentType.GROUP_SINGLE_CHOSEN) {
                    if (ListHelper.isNullEmpty(component.getSingleChosen())) {
                        throw new RpcServerLogicalException(1, component.getName() + "选项不能为空");
                    }
                }
                if (component.getType() == ContentType.GROUP_MULTI_CHOSEN) {
                    if (ListHelper.isNullEmpty(component.getMultipleChosen())) {
                        throw new RpcServerLogicalException(1, component.getName() + "选项不能为空");
                    }
                }
            }
        }
    }
}
